﻿using Abp.Application.Services;
using Abp.Application.Services.Dto;
using Abp.Domain.Repositories;
using AppFramework.DinosaursParkMes.BOM.Dto;
using AppFramework.DinosaursParkMes.DictionariesModel;
using AppFramework.DinosaursParkMes.DomainService.CodingRule;
using AppFramework.DinosaursParkMes.Material.Dto;
using AppFramework.DinosaursParkMes.MaterialModel;
using AppFramework.DinosaursParkMes.Product;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Org.BouncyCastle.Math.EC.Rfc7748;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Twilio.Http;

namespace AppFramework.DinosaursParkMes.BOM
{
    public class BillOfMaterialService : AppFrameworkAppServiceBase, IBillOfMaterialService
    {
        private readonly IRepository<BillOfMaterial> _bomRepository;
        private readonly IRepository<BillOfMaterialDetails> _bomDetailsRepository;
        private readonly IRepository<Productinfo> _ProductRepository;
        private readonly IRepository<AppFramework.DinosaursParkMes.MaterialModel.Material> _MaterialRepository;
        private readonly IRepository<MaterialModel.Materialtype> _MaterialtypeRepository;
        private readonly IRepository<ProductClassification> _ProductClassrepository;
        private readonly ICodingruleManager _manager;
        public BillOfMaterialService(IRepository<BillOfMaterial> bomRepository, IRepository<BillOfMaterialDetails> bomDetailsRepository, IRepository<Productinfo> productRepository, IRepository<MaterialModel.Material> materialRepository, IRepository<Materialtype> materialtypeRepository, IRepository<ProductClassification> productClassrepository, ICodingruleManager manager = null)
        {
            _bomRepository = bomRepository;
            _bomDetailsRepository = bomDetailsRepository;
            _ProductRepository = productRepository;
            _MaterialRepository = materialRepository;
            _MaterialtypeRepository = materialtypeRepository;
            _ProductClassrepository = productClassrepository;
            _manager = manager;
        }

        /// <summary>
        /// BOM添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost, Route("CreateBOMData")]
        public async Task<int> CreateBOMData(BillOfMaterialDto model)
        {
            var billOfMaterialModel = ObjectMapper.Map<BillOfMaterial>(model);
            billOfMaterialModel.Numberbom= await _manager.GetCode("BillOfMaterial");
            billOfMaterialModel.CreationTime = DateTime.Now;
            billOfMaterialModel.CreatorUserId = 1;
            billOfMaterialModel.LastModificationTime = DateTime.Now;
            billOfMaterialModel.LastModifierUserId = 1;
            await _bomRepository.InsertAsync(billOfMaterialModel);
            var billOfMaterialDetailsModel = ObjectMapper.Map<List<BillOfMaterialDetails>>(model.MaterialData);

            foreach (var item in billOfMaterialDetailsModel)
            {
                item.CreationTime = DateTime.Now;
                item.CreatorUserId = 1;
                item.LastModificationTime = DateTime.Now;
                item.LastModifierUserId = 1;
                item.Numberbom = billOfMaterialModel.Numberbom;
                await _bomDetailsRepository.InsertAsync(item);
            }

            return 1;
        }
        /// <summary>
        /// BOM显示（ALL）
        /// </summary>
        /// <returns></returns>
        [HttpGet, Route("GetBOMAll")]
        public async Task<PagedResultDto<BOMDataOutDTO>> GetBOMList(BOMSelectPageDTO dto)
        {
            var res = new PagedResultDto<BOMDataOutDTO>();
            var bom = _bomRepository.GetAll();
            var list = from b in bom
                       select new BOMDataOutDTO
                       {
                           CreationTime = b.CreationTime,
                           Dailyproduction = b.Dailyproduction,
                           Defaultbom = b.Defaultbom,
                           Id = b.Id,
                           Numberbom = b.Numberbom,
                           Parentid = b.Parentid,
                           Processnumber = b.Processnumber,
                           Productmodel = b.Productmodel,
                           Productname = b.Productname,
                           Productnumber = b.Productnumber,
                           Remark = b.Remark,
                           Unit = b.Unit,
                           Versionnumber = b.Versionnumber,

                       };
            if (!string.IsNullOrEmpty(dto.ProductType))
            {
                list = list.Where(x => x.Productnumber.Equals(dto.ProductType) || x.Productname.Equals(dto.ProductType) || x.Productmodel.Equals(dto.ProductType));
            }
            if (!string.IsNullOrEmpty(dto.BOMVersion))
            {
                list = list.Where(x => x.Versionnumber.Equals(dto.BOMVersion));
            }
            if (!string.IsNullOrEmpty(dto.BOMNumber))
            {
                list = list.Where(x => x.Numberbom.Equals(dto.BOMNumber));
            }
            res.TotalCount = list.Count();
            res.Items = await list.OrderByDescending(p => p.Id).Skip((dto.PageIndex - 1) * dto.PageSize).Take(dto.PageSize).ToListAsync();

            return res;
        }
        [HttpGet, Route("GetBOMDetail")]
        public BOMDataOutDTO GetBOMData(string id)
        {
            if (id==""||id=="undefined")
            {
                return null;
            }
            try
            {
                var res = new BOMDataOutDTO();
               
                var data = _bomRepository.GetAllList().Where(x => x.Numberbom == id).FirstOrDefault();
                res = ObjectMapper.Map<BOMDataOutDTO>(data);
                res.CreationTimes = res.CreationTime.ToString("yyyy-MM-dd");
                res.LastModificationTimes = res.LastModificationTime.ToString("yyyy-MM-dd");
                var bom = new List<DetailData>();
                var list = _bomDetailsRepository.GetAllList().Where(m => m.Numberbom.Equals(id));
                var pro = _ProductRepository.GetAll();
                var protype = _ProductClassrepository.GetAll();
                var mate = _MaterialRepository.GetAll();
                var matetype = _MaterialtypeRepository.GetAll();

                foreach (var item in list)
                {
                    if (item.Accessorytype.Equals("2"))
                    {

                        var prodata = pro.Where(x => x.Productid.Equals(item.Materialnumber)).FirstOrDefault();
                        bom.Add(new DetailData
                        {

                            Materialnumber = item.Materialnumber,
                            Id = prodata.Id,
                            Name = prodata.Productname,
                            Accessorytype = item.Accessorytype,
                            MaterialclassifyName = protype.Where(x => x.Id == prodata.Productclassid).FirstOrDefault().Classname,
                            MaterialProperty = prodata.Productproperty,
                            Unit = prodata.Units,
                            Specificationsversion = prodata.Specification,
                            Materialtype = prodata.Producttype,


                        });
                    }
                    else
                    {
                        var matedata = mate.Where(x => x.Materialnumber.Equals(item.Materialnumber)).FirstOrDefault();
                        bom.Add(new DetailData
                        {

                            Materialnumber = item.Materialnumber,
                            Id = matedata.Id,
                            Name = matedata.Name,
                            Accessorytype = item.Accessorytype,
                            MaterialclassifyName = matetype.Where(x => x.Id == matedata.Materialclassify).FirstOrDefault().Name,
                            MaterialProperty = matedata.MaterialProperty,
                            Unit = matedata.Unit,
                            Specificationsversion = matedata.Specificationsversion,
                            Materialtype = matedata.Materialtype,
                        });
                    }

                }
                res.DetailList = bom;
                return res;
            }
            catch (Exception ex)
            {

                Console.WriteLine("BOM详情异常："+ex);
                return null;
            }
        }
       
    }
}
